/**
 * Copyright (C) 2013-2014 EaseMob Technologies. All rights reserved.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *     http://www.apache.org/licenses/LICENSE-2.0
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.adapter;

import java.util.Date;
import java.util.List;

import android.content.Context;
import android.graphics.drawable.BitmapDrawable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.Enum.InfoType;
import com.act.MyApplication;
import com.act.TopicListAct;
import com.control.UserControl;
import com.easemob.chat.EMContact;
import com.easemob.chat.EMConversation;
import com.easemob.chat.EMGroup;
import com.easemob.chat.EMGroupManager;
import com.easemob.chat.EMMessage;
import com.easemob.chat.ImageMessageBody;
import com.easemob.chat.TextMessageBody;
import com.easemob.exceptions.EaseMobException;
import com.easemob.util.DateUtils;
import com.xike.kyt.R;
import com.xike.util.MyUtil;
import com.xike.util.StringUtil;

/**
 * 显示所有聊天记录adpater
 * 
 */
public class ChatAllHistoryAdapter extends ArrayAdapter<EMConversation> {
	public static final String NEW_FRIENDS_USERNAME = "item_new_friends";
	public static final String GROUP_USERNAME = "item_groups";

	private LayoutInflater inflater;
	Context context;

	public ChatAllHistoryAdapter(Context context, int textViewResourceId, List<EMConversation> objects) {
		super(context, textViewResourceId, objects);
		inflater = LayoutInflater.from(context);
		this.context = context;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = inflater.inflate(R.layout.listitem_message, parent, false);
		}
		ViewHolder holder = (ViewHolder) convertView.getTag();
		if (holder == null) {
			holder = new ViewHolder();
			holder.tv_fromName = (TextView) convertView.findViewById(R.id.lvitem_message_tv_fromName);
			holder.tv_unReadNum = (TextView) convertView.findViewById(R.id.lvitem_message_tv_unReadNum);
			holder.tv_message = (TextView) convertView.findViewById(R.id.lvitem_message_tv_message);
			holder.tv_time = (TextView) convertView.findViewById(R.id.lvitem_message_tv_time);
			holder.tv_desc = (TextView) convertView.findViewById(R.id.lvitem_message_tv_desc);
			holder.img_avatar = (ImageView) convertView.findViewById(R.id.lvitem_message_img_userAvator);
			holder.msgState = convertView.findViewById(R.id.lvitem_message_img_msgState);
			holder.layout_item = (RelativeLayout) convertView.findViewById(R.id.lvitem_message_layout);

			convertView.setTag(holder);
		}
		// if (position % 2 == 0) {
		// holder.list_item_layout.setBackgroundResource(R.drawable.mm_listitem);
		// } else {
		// holder.list_item_layout.setBackgroundResource(R.drawable.mm_listitem_grey);
		// }

		// 获取与此用户/群组的会话
		EMConversation conversation = getItem(position);
		// 获取用户username或者群组groupid
		String username = conversation.getUserName();
		int info_type = 0;

		if (conversation.getUnreadMsgCount() > 0) {
			// 显示与此用户的消息未读数
			holder.tv_unReadNum.setText(String.valueOf(conversation.getUnreadMsgCount()));
			holder.tv_unReadNum.setVisibility(View.VISIBLE);
		} else {
			holder.tv_unReadNum.setVisibility(View.INVISIBLE);
		}

		if (conversation.getMsgCount() != 0) {
			// 把最后一条消息的内容作为item的message内容
			EMMessage lastMessage = conversation.getLastMessage();
			TextMessageBody body = (TextMessageBody) lastMessage.getBody();
			// holder.message.setText(SmileUtils.getSmiledText(getContext(), getMessageDigest(lastMessage, (this.getContext()))),
			// BufferType.SPANNABLE);//含表情
			String strDesc = "", strTitle = "", strContent = "";
			strTitle = body.getMessage();
			try {
				strDesc = lastMessage.getStringAttribute("description");
			} catch (EaseMobException e) {
				e.printStackTrace();
			}
			try {
				strTitle = lastMessage.getStringAttribute("title");
			} catch (EaseMobException e) {
				e.printStackTrace();
			}
			try {
				username = lastMessage.getStringAttribute("sender");
				if (username.equals(UserControl.getLoginUserName())) {
					username = lastMessage.getStringAttribute("to");
				}
			} catch (EaseMobException e) {
				e.printStackTrace();
			}
			try {
				strContent = lastMessage.getStringAttribute("content");
			} catch (EaseMobException e) {
				e.printStackTrace();
			}
			try {
				info_type = lastMessage.getIntAttribute("info_type");
			} catch (EaseMobException e) {
				e.printStackTrace();
			}

			// 本地或者服务器获取用户详情，以用来显示头像和nick
			holder.img_avatar.setImageResource(R.drawable.default_user_avator);
			String userAvator = "";
			try {
				userAvator = lastMessage.getStringAttribute("avator");
			} catch (EaseMobException e) {
				e.printStackTrace();
			}
			BitmapDrawable bd = (BitmapDrawable) context.getResources().getDrawable(R.drawable.default_user_avator);
			MyUtil.displayImageView(context, userAvator, holder.img_avatar, MyUtil.getRoundedCornerBitmap(bd.getBitmap()), true);
			if (username.equals(GROUP_USERNAME)) {
				holder.tv_fromName.setText("群聊");

			} else if (username.equals(NEW_FRIENDS_USERNAME)) {
				holder.tv_fromName.setText("申请与通知");
			}
			if (username.length() > 15) {
				username = username.substring(0, 14) + "...";
			}
			holder.tv_fromName.setText(username);
			holder.tv_time.setText(DateUtils.getTimestampString(new Date(lastMessage.getMsgTime())));

			if (info_type == InfoType.People.getIntValue()) {
				holder.tv_message.setText(strContent);
				holder.tv_desc.setText(strTitle);
			} else {
				holder.tv_message.setText(strTitle);
				holder.tv_desc.setText(strDesc);
			}
			if (lastMessage.direct == EMMessage.Direct.SEND && lastMessage.status == EMMessage.Status.FAIL) {
				holder.msgState.setVisibility(View.VISIBLE);
			} else {
				holder.msgState.setVisibility(View.GONE);
			}
		}

		return convertView;
	}

	// private String getMessageDigest(EMMessage message) {
	// try {
	// int info_type = message.getIntAttribute("info_type");
	// if(info_type==InfoType.Question.getIntValue()){
	//
	// }
	//
	// } catch (EaseMobException e) {
	// e.printStackTrace();
	// }
	//
	// return "";
	// }

	// /**
	// * 根据消息内容和消息类型获取消息内容提示
	// *
	// * @param message
	// * @param context
	// * @return
	// */
	// private String getMessageDigest(EMMessage message, Context context) {
	// String digest = "";
	// switch (message.getType()) {
	// case LOCATION: // 位置消息
	// if (message.direct == EMMessage.Direct.RECEIVE) {
	// // 从sdk中提到了ui中，使用更简单不犯错的获取string的方法
	// // digest = EasyUtils.getAppResourceString(context,
	// // "location_recv");
	// digest = getStrng(context, R.string.location_recv);
	// digest = String.format(digest, message.getFrom());
	// return digest;
	// } else {
	// // digest = EasyUtils.getAppResourceString(context,
	// // "location_prefix");
	// digest = getStrng(context, R.string.location_prefix);
	// }
	// break;
	// case IMAGE: // 图片消息
	// ImageMessageBody imageBody = (ImageMessageBody) message.getBody();
	// digest = getStrng(context, R.string.picture) + imageBody.getFileName();
	// break;
	// case VOICE:// 语音消息
	// digest = getStrng(context, R.string.voice);
	// break;
	// case VIDEO: // 视频消息
	// digest = getStrng(context, R.string.video);
	// break;
	// case TXT: // 文本消息
	// TextMessageBody txtBody = (TextMessageBody) message.getBody();
	// digest = txtBody.getMessage();
	// break;
	// case FILE: // 普通文件消息
	// digest = getStrng(context, R.string.file);
	// break;
	// default:
	// System.err.println("error, unknow type");
	// return "";
	// }
	//
	// return digest;
	// }

	private static class ViewHolder {
		/** 和谁的聊天记录 */
		TextView tv_fromName;
		/** 消息未读数 */
		TextView tv_unReadNum;
		/** 最后一条消息的内容 */
		TextView tv_message;
		/** 最后一条消息的时间 */
		TextView tv_time;
		/** 最后一条消息的描述 */
		TextView tv_desc;
		/** 用户头像 */
		ImageView img_avatar;
		/** 最后一条消息的发送状态 */
		View msgState;
		/** 整个list中每一行总布局 */
		RelativeLayout layout_item;

	}

}
